package com.xiaoxing.zhinenghuacangku_jining.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.printer.IDzPrinter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.zhinenghuacangku_jining.R;
import com.xiaoxing.zhinenghuacangku_jining.R2;
import com.xiaoxing.zhinenghuacangku_jining.di.component.DaggerJiNing_DianBiaoAGVRuKuComponent;
import com.xiaoxing.zhinenghuacangku_jining.di.module.JiNing_DianBiaoAGVRuKuModule;
import com.xiaoxing.zhinenghuacangku_jining.mvp.contract.JiNing_DianBiaoAGVRuKuContract;
import com.xiaoxing.zhinenghuacangku_jining.mvp.model.entity.JiNing_GetDistributeList;
import com.xiaoxing.zhinenghuacangku_jining.mvp.model.entity.JiNing_GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_jining.mvp.presenter.JiNing_DianBiaoAGVRuKuPresenter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.adapter.JiNing_XianshiAdapter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.Baocunmidnum;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.BaocunmidnumDao;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.DaoMaster;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.DaoSession;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.NoChongfuSelect;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.NoChongfuSelectDao;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.QuedingMaterial;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.dbbase.QuedingMaterialDao;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_DianBiaoAGVRuKu;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_RuKuDaiJianQuResult;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_XinyemianhuanchongweiBean;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.utils.LogWriter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.utils.PrinterQRUtil;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.utils.PrinterUtil;

import org.greenrobot.greendao.query.QueryBuilder;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_JINING_ACTIVITY_NAN_JING_LU__DIAN_BIAO_A_G_V_RU_KU)
public class JiNing_DianBiaoAGVRuKuActivity extends BaseActivity<JiNing_DianBiaoAGVRuKuPresenter> implements JiNing_DianBiaoAGVRuKuContract.View, EasyPermissions.PermissionCallbacks, PrinterUtil.PrinterI {

    @BindView(R2.id.nice_storage)
    NiceSpinner spStorage; //物料下拉选
    @BindView(R2.id.nice_position_cang_wei)
    NiceSpinner spPosition; //仓位下拉选
    @BindView(R2.id.ll_cang_wei)
    LinearLayout llCangWei;
    @BindView(R2.id.ll_sou_suo_wu_liao)
    LinearLayout ll_sou_suo_wu_liao;
    @BindView(R2.id.btn_scan_qr_code)
    Button btnScanQrCode;
    @BindView(R2.id.btn_generate_tags)
    Button btnGenerateTags;
    @BindView(R2.id.btn_confirm_storage)
    Button btnConfirmStorage;
    @BindView(R2.id.btn_scan_mid)
    Button btnScanMid; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.cb_er_wei_ma)
    CheckBox cbErWeiMa; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.cb_zi_dong_ku_wei)
    CheckBox cbZiDongKuWei; //是否自动选择库位
    @BindView(R2.id.et_dan_hao)
    EditText etDanHao;
    @BindView(R2.id.et_xiang_mu_ming_cheng)
    EditText etXiangMuMingCheng;
    @BindView(R2.id.et_xiang_mu_bian_hao)
    EditText etXiangMuBianHao;
    @BindView(R2.id.et_wu_liao_ming_cheng)
    EditText etWuLiaoMingCheng;
    @BindView(R2.id.et_gong_ying_shang)
    EditText etGongYingShang;
    @BindView(R2.id.tv_cha_xun)
    TextView tvChaXun;
    @BindView(R2.id.et_weizhi)
    EditText etWeizhi;
    @BindView(R2.id.tv_check)
    TextView tvCheck;
    @BindView(R2.id.tv_agv_huan_chong_wei)
    TextView tvAgvHuanChongWei;
    @BindView(R2.id.et_num)
    EditText et_num;
    @BindView(R2.id.et_remark)

    EditText et_remark;
    ListView lv_xianshi;

    PrinterUtil mPrinterUtil;
    TextView tv_huanchongwei;
    Button btn_commit_ruku;
    BaocunmidnumDao baocunmidnumDao;
    NoChongfuSelectDao noChongfuSelectDao;
    QuedingMaterialDao quedingMaterialDao;
    TextView tv_chakan;
    List<QuedingMaterial> listy;
    ArrayList<String> list;
    JiNing_XianshiAdapter mAdapters;
    List<String> nlist;

    boolean diaoyong = false;
    NiceSpinner nice_position_cang_weis;
    String y = "";
    private BottomDialogUtil mBottomDialogUtilShare;
    private boolean isScan = false; //是否扫描二维码
    private boolean isGenerateTags = false; // 是否生成、打印标签
    private boolean isConfirmStorage = false; //是否确定入库
    private int did = 0;
    private double num = 0;
    private int mIselecmeter = 0; // 1 表示电表 要入2号堆垛机 0 其他物料 入1号堆垛机
    private String imgStr = "";
    private String cangWeiPosition = "";
    private String mid = "";
    private String instoreBufferId = "";
    private int spid = 0; //仓位、库位
    private String spname = "";
    private TextWatcher numTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String etNum = et_num.getText().toString();
            if (!TextUtils.isEmpty(etNum) && Double.parseDouble(etNum) > 0) {
                if (Double.parseDouble(etNum) > num) {
//                    et_num.setText(num + "");
                    showMessage("数量不能大于" + num);
                    return;
                }
//                num = Double.parseDouble(et_num.getText().toString());
            }


        }

        @Override
        public void afterTextChanged(Editable s) {

            y = et_num.getText().toString();
        }
    };
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private String mOrderNo = "";
    private String mWuLiaoMingCheng = "";
    private String mXiangMuBianHao = "";
    private LogWriter mLogWriter;
    private int mGid = 0;
    private String mSptname;
    private String mScanSpid = "";
    /**
     * 初始化缓冲位列表下拉选
     */
    private ArrayList<String> mSpids;
    private String mScanMid = "";
    private boolean isRuKuDaiJianKu = false;
    private String selectedKuWeiId = ""; //已选择的库位id，可以选择多个物料
    private boolean isHasTask = false;

    public static byte[] strToByteArray(String str) {
        if (str == null) {
            return null;
        }
        byte[] byteArray = str.getBytes();
        return byteArray;
    }

    public static Bitmap getBitmap(String filePath) {

        Bitmap bitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
                (double) options.outWidth / 1024f,
                (double) options.outHeight / 1024f)));
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        return bitmap;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerJiNing_DianBiaoAGVRuKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .jiNing_DianBiaoAGVRuKuModule(new JiNing_DianBiaoAGVRuKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_ji_ning_activity_dian_biao_a_g_v_ru_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_nan_jing_lu__dian_biao_a_g_v_ru_ku));

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(JiNing_DianBiaoAGVRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        baocunmidnumDao = daoSession.getBaocunmidnumDao();
        noChongfuSelectDao = daoSession.getNoChongfuSelectDao();
        quedingMaterialDao = daoSession.getQuedingMaterialDao();
//        baocunmidnumDao.deleteAll();
        tv_huanchongwei = findViewById(R.id.tv_huanchongwei);
        btn_commit_ruku = findViewById(R.id.btn_commit_ruku);
        lv_xianshi = findViewById(R.id.lv_xianshi);
        tv_chakan = findViewById(R.id.tv_chakan);
        nice_position_cang_weis = findViewById(R.id.nice_position_cang_weis);
        gethuanchongwei();
        File logf = new File(Environment.getExternalStorageDirectory() + File.separator + "cangkuguanli-" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm") + ".txt");

        try {
            mLogWriter = LogWriter.open(logf.getAbsolutePath());
        } catch (Exception e) {
        }

        log("22222222222222222");
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView btnRight = findViewById(R.id.btnRight);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isHasTask) {
                    showConfirmMessageHasTaskDialog();
                } else {

                    if (diaoyong == true) {

                    } else {
                        cancelBufferReadyForAGV();
                    }

                    finish();

                }
            }
        });
        btnRight.setText("执行命令");
        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StartAGVInstoreTaskQingDao();
            }
        });
        PhotoUtil.init(this, new FrescoIniter());
//        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(false);
//        et_num.addTextChangedListener(numTextWatcher);


        btnScanQrCode.setText("扫描库位或扫描缓冲位");
        cbErWeiMa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isRuKuDaiJianKu)
                    if (isChecked) {
                        btnScanMid.setVisibility(View.VISIBLE);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanMid.setEnabled(true);

                        ll_sou_suo_wu_liao.setVisibility(View.GONE);
                        spStorage.setVisibility(View.GONE);
                        et_num.setVisibility(View.GONE);
//                        btnGenerateTags.setVisibility(View.GONE);
                    } else {
                        btnScanMid.setVisibility(View.GONE);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanQrCode.setEnabled(true);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanMid.setEnabled(false);

                        ll_sou_suo_wu_liao.setVisibility(View.VISIBLE);
                        spStorage.setVisibility(View.VISIBLE);
                        et_num.setVisibility(View.VISIBLE);
//                        btnGenerateTags.setVisibility(View.VISIBLE);

                    }
            }
        });
        cbErWeiMa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRuKuDaiJianKu) {
                    showMessage("您扫描的二维码在入库待检区库位中");
                }
            }
        });
        cbZiDongKuWei.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    getAutoChooseUserSpaceForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID));
                } else {
//                    try {
//                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = new ArrayList<>();
//                        initSpPosition(getUserSpaceListForAutoStoreList);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });
        cbZiDongKuWei.setChecked(true);
        btn_commit_ruku.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onClick(View v) {
                if (spid > 0) { //判断库位(仓位)，如果数据为0，不能执行发送命令操作，大于0是才能执行发送命令操作

                    if (TextUtils.isEmpty(selectedKuWeiId)) { //判断入库位置，如果入库位置变量为空，不能执行发送命令操作
                        showMessage("请选择入库位置");
                        return;
                    }
                    if (TextUtils.isEmpty(getDianBiaoShuLiang())) {
                        showMessage("电表数量不能为空");
                        return;
                    }

                    showConfirmMessageShuLiangDialog();
                } else {
                    Toast.makeText(JiNing_DianBiaoAGVRuKuActivity.this, "请选择入库仓位", Toast.LENGTH_LONG).show();
                }

            }
        });
        tv_chakan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listy = new ArrayList<>();
                mAdapters = new JiNing_XianshiAdapter(JiNing_DianBiaoAGVRuKuActivity.this, listy);
                lv_xianshi.setAdapter(mAdapters);
                ArrayList<QuedingMaterial> listss = (ArrayList<QuedingMaterial>) queryUserListqd();
                mAdapters.addAll(listss);
            }
        });

    }

    public void zhiXingCunRuMingLing() {
        showLoading();
        //电表入库不需要打印二维码
        String methodName = "SaveElecMeterInstoreOrder";
        SoapParams params = new SoapParams();
        params.put("num", getDianBiaoShuLiang());
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID)); //登录用户的id
        params.put("instoreBufferId", selectedKuWeiId);
        params.put("spid", String.valueOf(spid)); //仓位、库位id
        params.put("remark", et_remark.getText().toString().trim()); //备注

        SoapUtil.getInstance(JiNing_DianBiaoAGVRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    int a = Integer.parseInt(result);
                    //成功 返回大于0的数 验证失败 返回-100  接口服务异常 返回-1  提交数据错误 返回0
                    if (a > 0) {
                        showMessage("命令发送成功");
                        isHasTask = true;
                        selectedKuWeiId = ""; //命令发送成功后把入库位变量置空
                        et_num.setText("");

                        diaoyong = true;
//                        baocunmidnumDao.deleteAll();

                        if (cbZiDongKuWei.isChecked()) { //如果自动选择库位勾选，则执行自动查询仓位方法
                            getAutoChooseUserSpaceForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID));
                        } else {//如果自动选择库位没有勾选，则执行手动查询仓位方法
                            cangWeiChaXun();
                        }
                    } else {
                        showMessage("命令发送失败");
                        diaoyong = true;
//                        baocunmidnumDao.deleteAll();
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                showMessage(content);
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                showMessage(fault.getMessage());

            }
        }, getAapiUserName(), getApiPwd());
    }

    public void gethuanchongwei() {
        showLoading();

        String methodNames = "GetBatchFreeInstoreBuffer";
        SoapParams paramss = null;
        paramss = new SoapParams();
        SoapUtil.getInstance(JiNing_DianBiaoAGVRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {

                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<JiNing_XinyemianhuanchongweiBean> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, JiNing_XinyemianhuanchongweiBean.class);
                        inHuanChongs(getUserSpaceListForAutoStoreList);


                    } else {
                        if (nice_position_cang_weis != null) {
                            nice_position_cang_weis.clearData();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @SuppressLint("LongLogTag")
    private void cancelBufferReadyForAGV() {


//        String methodName = "CancelBufferReadyForAGV";
//
//        SoapParams params = new SoapParams();
//        params.put("bufferId", bufferId);

        showLoading();

        ArrayList<Baocunmidnum> listss = (ArrayList<Baocunmidnum>) queryUserListyanshouss();
        JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
        String methodName = "RollBackInstoreBatch";
        SoapParams params = new SoapParams();
        params.put("modelJson", jsonArray.toJSONString());
        params.put("instoreBufferId", selectedKuWeiId);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();

//result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")
                if (result.equals(true)) {
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                    finish();
                } else {
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    //自动获得库位
    private void getAutoChooseUserSpaceForAutoStore(String user_id) {

        showLoading();

        String methodName = "AutoChooseUserSpaceForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("ismeter", "1");
        params.put("did", String.valueOf(did));
        LogUtils.debugEInfo("自动获得库位AutoChooseUserSpaceForAutoStoreQingDao==" + mIselecmeter);


        /**
         * 请求
         */

        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    gethuanchongwei();

                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        JiNing_GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = new Gson().fromJson(result, JiNing_GetUserSpaceListForAutoStore.class);

                        List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = new ArrayList<>();
                        if (getUserSpaceListForAutoStore != null) {
                            getUserSpaceListForAutoStoreList.add(getUserSpaceListForAutoStore);
                            initSpPosition(getUserSpaceListForAutoStoreList);
                        }

                    } else {
                        if (spPosition != null) {
                            spPosition.clearData();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    public List<QuedingMaterial> queryUserListqd() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(JiNing_DianBiaoAGVRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        quedingMaterialDao = daoSession.getQuedingMaterialDao();
        QueryBuilder<QuedingMaterial> qb = quedingMaterialDao.queryBuilder();
        List<QuedingMaterial> list = qb.list();
        return list;
    }

    private void inHuanChongs(List<JiNing_XinyemianhuanchongweiBean> xinyemianhuanchongweiBeans) {
        ArrayList<String> list = new ArrayList<String>();
        int selectedIndex = 0;
        HashMap<String, String> dataIds = new HashMap<>();

        for (int i = 0; i < xinyemianhuanchongweiBeans.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(xinyemianhuanchongweiBeans.get(i).getBuffer_name())
            ));
            dataIds.put(xinyemianhuanchongweiBeans.get(i).getBuffer_name(), xinyemianhuanchongweiBeans.get(i).getId());

            if (selectedKuWeiId != null && selectedKuWeiId.equals(xinyemianhuanchongweiBeans.get(i).getId())) {
                selectedIndex = i;
            }

        }
        nice_position_cang_weis.attachDataSource(list);
        LogUtils.debugEInfo("getBuffer_name==" + nice_position_cang_weis.getFullWidthAdapter().getItem(0));
        selectedKuWeiId = dataIds.get(nice_position_cang_weis.getFullWidthAdapter().getItem(0));
        LogUtils.debugEInfo("selectedKuWeiId==" + selectedKuWeiId);
        nice_position_cang_weis.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.debugEInfo("getBuffer_name==" + nice_position_cang_weis.getFullWidthAdapter().getItem(position));
                selectedKuWeiId = dataIds.get(nice_position_cang_weis.getFullWidthAdapter().getItem(position));
                LogUtils.debugEInfo("selectedKuWeiId==" + selectedKuWeiId);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {

                mScanSpid = extras.getString("scan_result");
                //判断扫描的二维码是否在返回的列表中(二维码为spid)
                if (mSpids.contains(mScanSpid)) { //在的话mScanSpid = spid
                    isRuKuDaiJianKu = true;
//                    btnGenerateTags.setVisibility(View.GONE);
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(true);
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(false);
                    hideCangWei();

                } else { //不在的话，给个提示，instoreBufferId = spid ，然后把mScanSpid置为空
                    isRuKuDaiJianKu = false;
                    mScanSpid = "";
                    showCangWei();
                    if (!cbErWeiMa.isChecked()) {
                        instoreBufferId = extras.getString("scan_result");
                        setInstoreBufferReadyForAGV(instoreBufferId, spname);
                    } else if (cbErWeiMa.isChecked()) {
                        instoreBufferId = extras.getString("scan_result");
//                        btnGenerateTags.setVisibility(View.GONE);
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnConfirmStorage.setEnabled(true);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanMid.setEnabled(false);

                    } else {
                        showMessage("您扫描的二维码不在入库待检区库位中");
                    }

                }

            }

        } else if (resultCode == 102) {//扫描物料二维码(有二维码的质检样品)
            Bundle extras = data.getExtras();
            mid = extras.getString("scan_result");
            mScanMid = mid;
//            btnGenerateTags.setVisibility(View.GONE);


            btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmStorage.setEnabled(false);
            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanQrCode.setEnabled(true);
            btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanMid.setEnabled(false);

        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void hideCangWei() {

        spPosition.setVisibility(View.GONE);
        llCangWei.setVisibility(View.GONE);
        btn_commit_ruku.setVisibility(View.GONE);


    }

    private void showCangWei() {

        spPosition.setVisibility(View.VISIBLE);
        llCangWei.setVisibility(View.VISIBLE);
    }

    private void setInstoreBufferReadyForAGV(String bufferId, String spid) {
        showLoading();

        String methodName = "SetInstoreBufferReadyForAGV";

        SoapParams params = new SoapParams();
        params.put("bufferId", bufferId);
        params.put("spname", spid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (result.equals("false")) {
                        LogUtils.debugEInfo("resultresultresultresult=" + result);
                        showMessage("缓冲位置不可用，请联系管理员");
                    } else {

                        isScan = true;
                        tvAgvHuanChongWei.setVisibility(View.VISIBLE);
                        tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
//                        btnGenerateTags.setBackgroundColor(getResources().getColor(R.color.public_red));
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
//                        btnGenerateTags.setEnabled(true);
                        btnConfirmStorage.setEnabled(false);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            xiuGaiTouXiang();
        }
    }

    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(JiNing_DianBiaoAGVRuKuActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    log("相册选择图片：");
//                                    if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
//                                        createMaterialForInstoreAuto(compressedPath);
//                                    } else {
//                                        imgStr = ArmsUtils.fileToBase64(compressedPath);
//                                    }

                                    if (isRuKuDaiJianKu) {
                                        imgStr = ArmsUtils.bitmapToString(compressedPath);
                                    } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {

                                    } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {

                                        createMaterialForInstoreAuto(compressedPath);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(JiNing_DianBiaoAGVRuKuActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    log("相机拍照：");
//                                    if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
//                                        createMaterialForInstoreAuto(compressedPath);
//                                    } else {
//                                        imgStr = ArmsUtils.fileToBase64(compressedPath);
//                                    }

                                    if (isRuKuDaiJianKu) {
                                        imgStr = ArmsUtils.bitmapToString(compressedPath);
                                    } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {

                                    } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
                                        createMaterialForInstoreAuto(compressedPath);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(JiNing_DianBiaoAGVRuKuActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    public void log(String msg) {

        try {
            mLogWriter.print(JiNing_DianBiaoAGVRuKuActivity.class, msg);
        } catch (Exception e) {
        }
    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        imgStr = ArmsUtils.bitmapToString(compressedPath);
//        HashMap<String, String> map = new HashMap<String, String>();
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));//运输计划ID
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("num", et_num.getText().toString());
        params.put("imgStr", String.valueOf(imgStr));
        log("调用上传图片接口");

        noChongfuSelectDao.insert(new NoChongfuSelect(String.valueOf(did)));
//        mPresenter.createMaterialForInstoreAuto(StorageActivity.this, map);
        createMaterialForInstoreAuto(params);
    }

    private void createMaterialForInstoreAuto(SoapParams params) {
        showLoading();


        String methodName = "CreateMaterialForInstoreAuto";


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (!result.equals("-1")) {
                        mid = result;

                        baocunmidnumDao.insert(new Baocunmidnum(mid, et_num.getText().toString()));
                        log("上传图片成功后返回的要打印的mid：" + result);
                        try {

                            if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                                printQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            } else {
//                                printBigQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                                PrinterQRUtil.printBigQRcodeOriention(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            }
                        } catch (Exception e) {
                            log(e.getMessage());
                        }
                    } else {
                        RollBackInstoreBatch();


                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 小的纸张 50x20 的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 16 * 100, 0 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 15) {
            if (name.substring(15).length() > 20) {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 96 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 18 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("入库时间:" + time, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printQRcode");


//        }
    }

    public void RollBackInstoreBatch() {
        showMessage("打印异常");
        showLoading();

        ArrayList<Baocunmidnum> listss = (ArrayList<Baocunmidnum>) queryUserListyanshouss();
        JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
        String methodName = "RollBackInstoreBatch";
        SoapParams params = new SoapParams();
        params.put("modelJson", jsonArray.toJSONString());
        params.put("instoreBufferId", selectedKuWeiId);

        /**
         * 请求
         */
        SoapUtil.getInstance(JiNing_DianBiaoAGVRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();

//result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")
                if (result.equals(true)) {
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                    finish();
                } else {
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    public List<Baocunmidnum> queryUserListyanshouss() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(JiNing_DianBiaoAGVRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        baocunmidnumDao = daoSession.getBaocunmidnumDao();
        QueryBuilder<Baocunmidnum> qb = baocunmidnumDao.queryBuilder();
        List<Baocunmidnum> list = qb.list();
        return list;
    }

    /**
     * 大的纸张 50x50的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printBigQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printBigQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 50 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 10 * 100, 6 * 100, 25 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 0 * 100, 32 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 25) {
            if (name.substring(25).length() > 20) {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 0 * 100, 50 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("入库时间:" + time, 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printBigQRcode");

//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isHasTask) {
                showConfirmMessageHasTaskDialog();
            } else {

                if (!TextUtils.isEmpty(instoreBufferId)) {
                    showConfirmMessageDialog();
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                } else {
                    baocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                    if (diaoyong == true) {

                    } else {
                        cancelBufferReadyForAGV();
                    }
                    finish();

                }
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);


    }

    private void showConfirmMessageDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认退出?")
                .setMessage("已扫描缓冲位,确认退出?")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
//                        mPresenter.cancelBufferReadyForAGV(getContext(), instoreBufferId);
                        cancelBufferReadyForAGV();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showConfirmMessageHasTaskDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认执行命令?")
                .setMessage("有命令未执行,确认执行命令?")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        StartAGVInstoreTaskQingDao();
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showConfirmMessageShuLiangDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("确认电表数量?")
                .setMessage("电表数量： " + getDianBiaoShuLiang())
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        zhiXingCunRuMingLing();
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @NonNull
    private String getDianBiaoShuLiang() {
        return et_num.getText().toString().trim();
    }

    private void StartAGVInstoreTaskQingDao() {
        showLoading();

        String methodNames = "StartAGVInstoreTaskQingDao";
        SoapParams paramss = null;
        paramss = new SoapParams();
        SoapUtil.getInstance(JiNing_DianBiaoAGVRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {

                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        showMessage("执行命令成功");
                        isHasTask = false;
                    } else {
                        showMessage("执行命令失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                showMessage(content);
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                showMessage(fault.getMessage());
            }
        }, getAapiUserName(), getApiPwd());
    }

    @OnClick({R2.id.btn_scan_qr_code, R2.id.btn_generate_tags, R2.id.btn_confirm_storage, R2.id.btn_scan_mid})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_scan_qr_code) {
            if (getPermission()) {

                if (spid > 0) {

//            Utils.navigation(StorageActivity.this, RouterHub.ZHI_NENG_HUA_CANG_KU_SCAN_QR_CODE_ACTIVITY, 101);
                    Intent newIntent = new Intent(this, JiNing_ScanQRCodeActivity.class);
                    mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
                    // 开始一个新的 Activity等候返回结果
                    startActivityForResult(newIntent, 101);
                } else {
                    showMessage("请先选择仓位");
                }

            }

        } else if (i == R.id.btn_scan_mid) {//扫描物料二维码(有二维码的质检样品)
            if (getPermission()) {


                Intent newIntent = new Intent(this, JiNing_ScanQRCodeActivity.class);
                mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 102);
                // 开始一个新的 Activity等候返回结果
                startActivityForResult(newIntent, 102);


            }

        } else if (i == R.id.btn_generate_tags) {

            if (mPrinterUtil.selectPrinterCheck()) {

                //num 用于判断是否选择物料
                if (did > 0 && num > 0) {

//                    if (!isScan) {
//                        showMessage("请先扫描二维码");
//                        return;
//                    }
                    if (getPermission()) {
                        xiuGaiTouXiang();
                    }
                } else {
                    showMessage("请先选择物料");

                }
            }

        } else if (i == R.id.btn_confirm_storage) {
            if (getPermission()) {

                if (isRuKuDaiJianKu) {
                    //入库待检区
                    if (TextUtils.isEmpty(imgStr)) {
                        xiuGaiTouXiang();
                    } else {
                        linYinShouDongRuKu(mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                    }
                } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {
                    //有质检二维码的
                    if (spid > 0) {
                        linYinYouErWeiMaZhiJianYangPin(mScanMid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                    } else {
                        showMessage("请先选择仓位");

                    }

                } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
                    //一般入库,没有质检二维码的

                    if (!isScan) {
                        ArmsUtils.makeText(getContext(), "请先扫描二维码");
                        return;
                    }
                    if (!isGenerateTags) {
                        ArmsUtils.makeText(getContext(), "标签没有打印");
                        return;
                    }
                    addAgvTask(mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                }
            }


        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void addAgvTask(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "InstoreCallAGV";
        SoapParams params = new SoapParams();

        //(2)入库函数 public string Instore(int did, int spid, int uid, double num, int status, string remark, string imgStr)
        //判断mScanSpid是否为空，不为空二维码在返回的仓位列表中，执行Instore 方法，为空的话执行InstoreCallAGV 方法
//        if (!TextUtils.isEmpty(mScanSpid)) {
//            methodName = "Instore";
//            params.put("did", String.valueOf(did));
//            params.put("spid", mScanSpid);
//            params.put("uid", uid);
//            params.put("num", num);
//            params.put("status", "2");
//            params.put("remark", remark);
//            params.put("imgStr", imgStr);
//        } else if (cbErWeiMa.isChecked()) {
//            methodName = "InstoreCallAGVFromQualityZone";
//            params.put("mid", mid);
//            params.put("instoreBufferId", instoreBufferId);
//            params.put("spid", spid);
//            params.put("num", num);
//            params.put("uid", uid);
//            params.put("remark", remark);
//        } else {
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("num", num);
        params.put("uid", uid);
        params.put("remark", remark);
//        }


        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    isGenerateTags = false;
                    isRuKuDaiJianKu = false;
                    isScan = false;
                    btnScanQrCode.setBackgroundColor(getResources().getColor(R.color.public_red));
//                    btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(true);
//                    btnGenerateTags.setEnabled(false);
                    btnConfirmStorage.setEnabled(false);
                    onChaXunClicked();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinYouErWeiMaZhiJianYangPin(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "InstoreCallAGVFromQualityZone";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("uid", uid);
        params.put("remark", remark);


        /**
         * 请求
         */

        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    mScanMid = "";
                    showMessage("发送成功");
                    isGenerateTags = false;
                    isScan = false;
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(false);
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(false);
                    btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnScanMid.setEnabled(true);
                    onChaXunClicked();
//                    cangWeiChaXun();
                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinShouDongRuKu(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "Instore";
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));
        params.put("spid", mScanSpid);
        params.put("uid", uid);
        params.put("num", num);
        params.put("status", "2");
        params.put("remark", remark);
        params.put("imgStr", imgStr);


        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    showMessage("发送成功");
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnScanQrCode.setEnabled(true);
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(false);
                    try {
                        JiNing_RuKuDaiJianQuResult ruKuDaiJianQuResult = new Gson().fromJson(result, JiNing_RuKuDaiJianQuResult.class);
                        result = String.valueOf(ruKuDaiJianQuResult.getMid());
                        if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                            printQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        } else {
//                            printBigQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            PrinterQRUtil.printBigQRcodeOriention(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        }
                    } catch (Exception e) {
                        log(e.getMessage());
                    }
                    onChaXunClicked();
//                    cangWeiChaXun();

                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        showMessage("相关权限获取成功");

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showMessage("请同意相关权限，否则功能无法使用");

    }


    /**
     * 初始化入库列表下拉选
     */
    private void initSpStorage(List<JiNing_GetDistributeList> distributeLists) {

//ArrayList<String>
        list = new ArrayList<String>();
        HashMap<String, JiNing_GetDistributeList> getDistributeListHashMap = new HashMap<>();

        if (distributeLists.size() > 0) {
            for (int i = 0; i < distributeLists.size(); i++) {
                list.add(String.valueOf(
                        new StringBuilder()
                                .append(distributeLists.get(i).getProjectName())
                                .append("-")
                                .append(distributeLists.get(i).getMaterial())
                                .append("-")
                                .append(distributeLists.get(i).getDid())
                ));
                getDistributeListHashMap.put(distributeLists.get(i).getProjectName() + "-" + distributeLists.get(i).getMaterial() + "-" + distributeLists.get(i).getDid(), distributeLists.get(i));

            }


            spStorage.attachDataSource(list);

            JiNing_GetDistributeList getDistributeList = getDistributeListHashMap.get(spStorage.getFullWidthAdapter().getItem(0));

            did = getDistributeList.getDid();
            num = getDistributeList.getDnum();
//            et_num.setText(String.valueOf(num));
            mOrderNo = getDistributeList.getPurchaseid();//打印二维码的订单号
            mWuLiaoMingCheng = getDistributeList.getMaterial();//打印二维码的物料名称
            mXiangMuBianHao = getDistributeList.getProid();//打印二维码的项目编号
            mGid = getDistributeList.getGid();
            mIselecmeter = getDistributeList.getIselecmeter();

            LogUtils.debugEInfo("did=====" + did);
            LogUtils.debugEInfo("mIselecmeter==" + mIselecmeter);


            spStorage.setGravity(Gravity.LEFT);
            spStorage.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                @SuppressLint("LongLogTag")
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    JiNing_GetDistributeList getDistributeList = getDistributeListHashMap.get(spStorage.getFullWidthAdapter().getItem(0));

                    did = getDistributeList.getDid();
                    num = getDistributeList.getDnum();
//                    et_num.setText(String.valueOf(num));
                    mOrderNo = getDistributeList.getPurchaseid();//打印二维码的订单号
                    mWuLiaoMingCheng = getDistributeList.getMaterial();//打印二维码的物料名称
                    mXiangMuBianHao = getDistributeList.getProid();//打印二维码的项目编号
                    mGid = getDistributeList.getGid();
                    mIselecmeter = getDistributeList.getIselecmeter();

                    LogUtils.debugEInfo("did=====" + did);
                    LogUtils.debugEInfo("mIselecmeter==" + mIselecmeter);
                    LogUtils.debugEInfo("mIselecmeter==onItemClick=" + mIselecmeter);


                    quedingMaterialDao.insert(new QuedingMaterial(getDistributeList.getProjectName(), getDistributeList.getMaterial(), et_num.getText().toString()));


                }
            });
        } else {
            showMessage("未查询到该物料，请重新查询");
            list.add("");
            spStorage.attachDataSource(list);
            spStorage.setGravity(Gravity.LEFT);
        }


//        cangWeiChaXun();

    }


    private void initSpPosition(List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> spnames = new ArrayList<String>();
        mSpids = new ArrayList<String>();
        HashMap<String, JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreHashMap = new HashMap<>();

        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            spnames.add(String.valueOf(
                    new StringBuilder()
                            .append(getUserSpaceListForAutoStoreList.get(i).getSpname())
            ));
            if (getUserSpaceListForAutoStoreList.get(i).getSptname().equals("入库待检区")) {
                mSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            }
            getUserSpaceListForAutoStoreHashMap.put(getUserSpaceListForAutoStoreList.get(i).getSpname(), getUserSpaceListForAutoStoreList.get(i));
        }
        spPosition.attachDataSource(spnames);
        LogUtils.debugEInfo("spPosition.getFullWidthAdapter().getItem(0)=" + spPosition.getFullWidthAdapter().getItem(0));

        JiNing_GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(0));

        spid = getUserSpaceListForAutoStore.getSpid();
        spname = getUserSpaceListForAutoStore.getSpname();
        cangWeiPosition = String.valueOf(getUserSpaceListForAutoStore.getSpid());
        mSptname = getUserSpaceListForAutoStore.getSptname();

        LogUtils.debugEInfo("spid==" + spid);


        if (getUserSpaceListForAutoStore.getSptname().equals("入库待检区")) {
            hideCangWei();
        } else {

            btn_commit_ruku.setVisibility(View.VISIBLE);
        }

        if (mSptname.equals("入库待检区")) {
//                showMessage("仓管员扫描待检区二维码");
        }

        spStorage.setGravity(Gravity.LEFT);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.debugEInfo("spPosition.getFullWidthAdapter().getItem(position)=" + spPosition.getFullWidthAdapter().getItem(position));

                JiNing_GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(position));

                cangWeiPosition = String.valueOf(getUserSpaceListForAutoStore.getSpid());
                spid = getUserSpaceListForAutoStore.getSpid();
                spname = getUserSpaceListForAutoStore.getSpname();
                mSptname = getUserSpaceListForAutoStore.getSptname();

                LogUtils.debugEInfo("spid==" + spid);


                if (mSptname.equals("入库待检区")) {
//                        showMessage("仓管员扫描待检区二维码");
                }


                if (getUserSpaceListForAutoStore.getSptname().equals("入库待检区")) {
                    btn_commit_ruku.setEnabled(false);
                    tv_huanchongwei.setText(spname);
                    hideCangWei();

                } else {
                    btn_commit_ruku.setEnabled(true);
                }

            }
        });
    }


    @OnClick(R2.id.tv_check)
    public void cangWeiChaXun() {
        getUserSpaceListForAutoStore(getCangWei());
    }

    /**
     * 查询仓位
     *
     * @param spname
     */
    private void getUserSpaceListForAutoStore(String spname) {
        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), spname, mGid);
    }

    private String getCangWei() {
        return etWeizhi.getText().toString().trim();
    }

    /**
     * 选仓位
     * 用法同GetUserSpaceList
     * 多了一个字段 isauto，表明此仓位是否为立库仓位  用于提示用户
     *
     * @param user_id
     * @param spname  仓位的名字，为空的时候表示查询所有的
     * @return
     */

    @SuppressLint("LongLogTag")
    private void getUserSpaceListForAutoStore(String user_id, String spname, int gid) {
        showLoading();


        String methodName = "GetUserSpaceListForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        params.put("ismeter", "1"); //电表默认是1
        LogUtils.debugEInfo("选仓位GetUserSpaceListForAutoStoreQingDao==" + mIselecmeter);

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    gethuanchongwei();

                    String result = object.getProperty(finalMethodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, JiNing_GetUserSpaceListForAutoStore.class);
                        initSpPosition(getUserSpaceListForAutoStoreList);

                    } else {
                        if (spPosition != null) {
                            spPosition.clearData();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    public List<NoChongfuSelect> queryUserList() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(JiNing_DianBiaoAGVRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        noChongfuSelectDao = daoSession.getNoChongfuSelectDao();
        QueryBuilder<NoChongfuSelect> qb = noChongfuSelectDao.queryBuilder();
        List<NoChongfuSelect> list = qb.list();
        return list;
    }

    @OnClick(R2.id.tv_cha_xun)
    public void onChaXunClicked() {

        if (TextUtils.isEmpty(getDanHao())
                && TextUtils.isEmpty(getXiangMuMingCheng())
                && TextUtils.isEmpty(getXiangMuBianHao())
                && TextUtils.isEmpty(getWuLiaoMingCheng())
                && TextUtils.isEmpty(getGongYingShang())) {

            showMessage("至少输入一个查询条件");
            return;

        }

        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.UID))) {
            showMessage("请先登录");
            return;
        }
//        showCangWei();
//        mPresenter.getDistributeList(this, mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
        getDistributeList(mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
    }

    private String getDanHao() {
        return etDanHao.getText().toString().trim();
    }

    private String getXiangMuMingCheng() {
        return etXiangMuMingCheng.getText().toString().trim();
    }

    private String getXiangMuBianHao() {
        return etXiangMuBianHao.getText().toString().trim();
    }

    private String getWuLiaoMingCheng() {
        return etWuLiaoMingCheng.getText().toString().trim();
    }

    private String getGongYingShang() {
        return etGongYingShang.getText().toString().trim();
    }

    /**
     * 搜索获取物料列表
     *
     * @param user_id
     * @param orderNo
     * @param projectName
     * @param material
     * @param projectNo
     * @param sname
     * @return
     */
    private void getDistributeList(String user_id, String orderNo, String projectName, String material, String projectNo, String sname) {
        showLoading();


        String methodName = "GetDistributeList";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("orderNo", orderNo);
        params.put("projectName", projectName);
        params.put("material", material);
        params.put("projectNo", projectNo);
        params.put("sname", sname);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();


                String result = object.getProperty(methodName + "Result").toString();

                try {
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        List<JiNing_GetDistributeList> getDistributeLists = ArmsUtils.parseString2List(result, JiNing_GetDistributeList.class);
                        initSpStorage(getDistributeLists);

                        if (cbZiDongKuWei.isChecked()) { //如果自动选择库位勾选，则执行自动查询仓位方法
                            getAutoChooseUserSpaceForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID));
                        } else {//如果自动选择库位没有勾选，则执行手动查询仓位方法
                            cangWeiChaXun();
                        }
                    } else {
                        if (spStorage != null) {
                            spStorage.clearData();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void printQRcode(String content) {


        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30


        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {
        log(info);

    }

    @Override
    public void onPrintProgress(String info) {
        log(info);

    }

    @Override
    public void onPrinterDiscovery(String info) {
        log(info);

    }

    @Override
    public void connectSuccess(String info) {
        log("打印机连接成功，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void Connecting(String info) {
        log(info);

    }

    @Override
    public void connectFail(String info) {
        log("打印机连接失败、断开连接，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void printSuccess() {
        log("二维码打印成功");

        showQueDingRuKuBtn();
    }

    private void showQueDingRuKuBtn() {
        isGenerateTags = true;

        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
//        btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
        btnScanQrCode.setEnabled(false);
//        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(true);
    }

    @Override
    public void printFail() {
        log("二维码打印失败，请重新打印");
        showMessage("二维码打印失败，请重新打印");
        RollBackInstoreBatch();
    }

    @Override
    public void getJiNing_DianBiaoAGVRuKuDataSuccess(JiNing_DianBiaoAGVRuKu entityData) {


    }

    private void getJiNing_DianBiaoAGVRuKuData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getJiNing_DianBiaoAGVRuKuData(map);
    }
}
